package org.kia.activity.adapters;

import java.util.ArrayList;
import java.util.List;

import org.kia.R;
import org.kia.activity.SearchActivity;
import org.kia.data.model.CategoryModel;
import org.kia.data.model.ItemModel;
import org.kia.widgets.SimpleWebImageView;

import android.content.Context;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;

/**
 * List adapter for {@link SearchActivity}
 * 
 * @author Amir Lazarovich
 */
public class BusinessSearchListAdapter extends SearchListAdapter<ItemModel> implements ListAdapter {

	public BusinessSearchListAdapter(Context context) 
	{
		super(context);
	}

	private static final String TAG = "BusinessSearchListAdapter";

	@Override
	public View getView(int position, View converted, ViewGroup parent) {
		ViewHolder holder;

		if (converted == null) {
			converted = mInflater.inflate(R.layout.business_list_item, parent, false);
			holder = new ViewHolder();

			holder.image = (SimpleWebImageView) converted.findViewById(R.id.business_list_image);
			holder.image.setDefaultImageById(R.drawable.no_image);
			holder.name = (TextView) converted.findViewById(R.id.business_list_name);
			holder.address = (TextView) converted.findViewById(R.id.business_address);
			holder.phone = (TextView) converted.findViewById(R.id.business_phone);
			holder.distance = (TextView) converted.findViewById(R.id.business_distance);

			converted.setTag(holder);
		} else {
			holder = (ViewHolder) converted.getTag();
		}

		// Update our model view
		ItemModel model = getData().get(position);
		holder.name.setText(model.getName());
		holder.address.setText(model.getAddress());
		holder.phone.setText(model.getPhone());
		holder.distance.setText(String.valueOf(model.getDistance()));
		
		
		String oldImageUrl = holder.image.getLastImageUrl();
		if (model.getImage().equals(oldImageUrl)) {
			// Convert view didn't change since last time
			// thus there is no need to reset and load its image again
			return converted;
		}

		// calling reset is important to prevent old images from displaying in a recycled view.
		holder.image.reset();
		holder.image.setImageUrl(model.getImage());

		return converted;
	}

	// ////////////////////////////////////////////
	// Inner classes
	// ////////////////////////////////////////////

	/**
	 * ViewHolder pattern (used to decrease calls to findViewById method)
	 */
	static class ViewHolder {
		SimpleWebImageView image;
		TextView name;
		TextView address;
		TextView phone;
		TextView distance;
		
	}

}
